package cyh.service.array;

import cyh.domain.dto.BaseDto;
import cyh.domain.entity.BaseEntity;
import cyh.domain.vo.BaseVo;
import cyh.domain.vo.Result;
import cyh.service.IBaseService;

import java.util.Arrays;

/**
 * 业务层—基类
 *
 * @author 侯骏辉
 * @since 2025/6/1 23:11
 */
abstract class BaseService<
        Entity extends BaseEntity,
        Dto extends BaseDto,
        Vo extends BaseVo
        > implements IBaseService < Entity, Dto>{

    static final int DATE_SIZE = 100;
    Entity[] data;
    Vo[] temp;
    private int idCounter = 1;

    abstract Vo convertToVo(Entity entity);
    abstract Entity createEntity(Dto dto, int id);
    @Override
    public Result list() {
        int length = 0;
        for (int i = 1; i < idCounter; i++) {
            if (data[i] != null) temp[length++] = convertToVo(data[i]);
        }
        return Result.success("查询成功", Arrays.copyOf(temp, length));
    }

    @Override
    public Result create(Dto dto) {
        if (idCounter > DATE_SIZE) {
            return Result.failure("创建失败，超出了存储容量");
        }

        Entity entity = createEntity(dto, idCounter++);
        data[entity.getId()] = entity;
        return Result.success("创建成功", null);
    }

    @Override
    public Result update(Dto dto, int id) {
        if (!existById(id)) return Result.failure("更新失败，部门不存在");
        Entity entity = data[id];
        updateEntity(dto, entity);
        return Result.success("更新成功", null);
    }

    @Override
    public boolean existById(int id) {
        return id > 0 && id < idCounter && data[id] != null;
    }

    abstract void updateEntity(Dto dto, Entity entity);
    @Override
    public Entity findById(int id) {
        if (existById(id)) return data[id];
        return null;
    }
}